import openpyxl
from openpyxl.worksheet.worksheet import Worksheet


class Excel:

    def __init__(self, file):
        self.file = file

    def open_folder(self, sheet_name) -> Worksheet:
        wb = openpyxl.load_workbook(self.file)
        sheets = wb[sheet_name]
        return sheets

    def headers(self, sheet_name):
        sheets = self.open_folder(sheet_name)
        price = sheets[1]
        list_headers = []
        for i in price:
            list_headers.append(i.value)
        return list_headers

    def read(self, sheet_name):
        sheets = self.open_folder(sheet_name)
        vive = list(sheets.rows)
        read_list = []
        for i in vive[1:]:
            vive_list = []
            for a in i:
                vive_list.append(a.value)
            data_name = dict(zip(self.headers(sheet_name), vive_list))
            read_list.append(data_name)
        return read_list

    @staticmethod
    def write(file, sheet_name, line, row, excel_data):
        wb = openpyxl.load_workbook(file)
        sheets = wb[sheet_name]
        sheets.cell(line, row).value = excel_data
        wb.save(file)
        wb.close()
        return "成功写入"

